
import Api, { SEARCH_GOODS } from '../../utils/api.js';
import { handPic, getUrl } from '../../utils/util.js';

const App = getApp();

Page({
    data: {
        fixed: false,                               // true条件筛选fixed定位 false 不使用fixed定位
        isSearch: true,                             // true展示搜索页 false展示结果页
        search_value: "",                           // 搜索内容
        default_search: "",
        screen_height: "",                          // 屏幕高度 
        result_list: {},                   // 搜索结果列表数据
        search_box_height: "",                      // 搜索容器高度
        hot_search: [],                     // 热门搜索列表数据
        price_filtering_show: false,                // true显示价格筛选 false隐藏
        search_history: [],             // 搜索历史数据
        filt_show: false,                                 //价格筛选是否显示
        next_page: '1',                                   //下一页
        isloading: false,                              // 是否加载中
        hasMore: false,                                 // 是否有更多
        sort:'default',
        price:0
    },
    //  ============  搜索页面 方法区 ==============
    // 设置搜索内容 set and clear 
    sort: function (e) {
        let sort = e.target.dataset.sort,
            _this = this;
        switch (sort) {
            case 'default':
            case 'sale':
            case 'new':
                this.setData({
                    sort: sort,
                    min_price: '',
                    max_price: '',
                    price: ''
                }, function () {
                    _this.loadList(1);
                })
                break;
            case 'price':
                const { price_filtering_show } = this.data;
                
                _this.setData({ price_filtering_show: !price_filtering_show })
                break;
        };

        // 如果点击的不是价格筛选 修改点击状态(价格筛选没有激活状态),关闭价格区间
        if (sort != 'price') {
            this.setData({ sort: sort });
        }

    },
    loadList:function(p){

        const { search_value,sort,price,list} = this.data;

        wx.showLoading({
            title: '加载中',
            mask: true
        })
        Api.fetch(SEARCH_GOODS, {price:price,sort:sort,skey: search_value,page:p}, resp => {
            resp.items.map((v, k) => {
                v.default_img = handPic(v.default_img, 4)
            })
            
            if (resp.page == 1) {
                this.setData({
                    list: resp.items
                })
            } else {
                this.setData({
                    list: list
                })
            }
            this.setData({
                hasMore: resp.page == resp.next ? false : true,
                p: resp.page,
            });
            wx.hideLoading();
        })
    },
    Close_filt: function (close = false) {
        let status, filt_show = this.data.filt_show;

        if (filt_show) {
            status = false
        } else {
            close ? status = false : status = true;
        }

        this.setData({ filt_show: status });
    },
    set_search_val: function (e) {

        const tip = e.target.dataset.tip;

        if (tip == "set") {
            if (e.type == "input") {
                this.setData({ search_value: e.detail.value })
            } else {
                this.setData({ search_value: e.target.dataset.value })
                this.search();
            }
        } else if (tip == "clear") {
            this.setData({ search_value: "" })
        }
    },

    search: function (e) {
        let { search_history, hot_search, search_value,sort,price} = this.data;
        let value = search_value.replace(/(^\s*)|(\s*$)/g, "");
        if (value){
            this.history_Storage('set', 'history', search_value);
            //获取搜索列表
            this.setData({ isSearch: false });

            Api.fetch(SEARCH_GOODS, { skey: search_value, sort: sort, price: price }, resp => {
                resp.items.map((v, k) => {
                    v.default_img = handPic(v.default_img, 4)
                })

                this.setData({
                    list: resp.items,
                    hasMore: resp.page == resp.next ? false : true,
                    p: 1,
                });
            })
            wx.setNavigationBarTitle({
                title: search_value,
            })
        }else{
            wx.showToast({
                title: '内容不能为空',
                icon: 'success',
                duration: 1000
            })
        }
       

    },
    clear: function () {
        this.history_Storage('clear', 'history');
        this.setData({ search_history: [] })
    },
    // 搜索历史缓存
    history_Storage: function (type, key, data) {
        // 设置搜索历史
        if (type == "set") {
            const that = this;
            wx.getStorage({
                key: key,
                success: function (res) {
                    if (data) {
                        const history_data = res.data;
                        // 先查是否已有相同数据
                        if (history_data.length > 0) {
                            history_data.map((item, idx) => {
                                if (item == data) {
                                    history_data.splice(idx, 1);
                                }
                            })
                        }
                        history_data.unshift(data);
                        wx.setStorageSync('history', history_data);
                        that.setData({ search_history: history_data });
                    }
                },
                fail: function (res) {
                    wx.setStorageSync('history', [])
                }
            })
            // 获取搜索历史
        } else if (type == 'get') {
            const history_data = wx.getStorageSync(key);
            if (history_data) {
                this.setData({ search_history: history_data })
            } else {
                wx.setStorageSync('history', []);
                this.setData({ search_history: [] })
            }
            // 清除搜索历史
        } else if (type == 'clear') {
            wx.setStorageSync('history', []);
            this.setData({ search_history: [] })
        }
    },
    //  ============  搜索页面 方法区 ==============


    //  ============  结果页面 方法区 ==============
    // 触底
    lower: function (e) {
        const {p,hasMore} = this.data;

        if (hasMore) {                              //是否有更多 
            this.loadList(p+1);
        }


    },
    filt_price: function (e) {
        // 按输入的区间搜索
        let _this = this;
        
        if (e.target.dataset.tip) {
            const { min_price, max_price } = this.data;
            if (min_price && max_price) {
                // 发起搜索请求 并且关闭价格搜索 同时修改数据
 
                this.setData({
                    price: min_price + "-" + max_price
                }, function () {
                    _this.loadList(1);
                })
                const { price_filtering_show } = this.data;
                _this.setData({ price_filtering_show: !price_filtering_show })
                
            } else {
                wx.showToast({
                    title: '请输入价格',
                    icon: 'success',
                    duration: 1000
                })
            }
        } else {
            let { price } = e.target.dataset;

            price = price.split("-");

            this.setData({
                min_price: price[0],
                max_price: price[1],
                price: e.target.dataset.price
            })
        }

    },
    priceSection: function (e) {
        let { tip } = e.target.dataset;
        let value = e.detail.value;

        if (tip == "min") {
            this.setData({ min_price: value });
        } else {
            this.setData({ max_price: value });
        }
    },
    // 判断价格筛选模块是否置顶
    scroll: function (e) {
        let status;
        const { search_box_height } = this.data;
        e.detail.scrollTop >= (search_box_height) ? status = true : status = false;
        this.setData({ fixed: status })
    },
    // 通用页面跳转
    navigateTo: function (e) {
        let url;
        const tip = e.currentTarget.dataset.tip;
        const idx = e.currentTarget.dataset.idx;


        if (tip == "search") {
            this.setData({ isSearch: true })
        } else if (tip == "notification") {
            url = '../mine/notification/notification';
        } else if (tip == 'goods_detail') {
            url = getUrl(tip, { gc_id: idx });
        }

        url ? App.navigateTo(url) : null;
        wx.setNavigationBarTitle({ title: "搜索" });

    },
    //  ============  结果页面 方法区 ==============
    // onLoad
    onLoad: function (options) {
        // 检索搜索历史是否有数据
        this.history_Storage("get", "history");
        // 获取并设置屏幕高度用于scroll-view
        const that = this;
        wx.getSystemInfo({
            success: function (res) {
                that.setData({
                    screen_height: res.windowHeight,
                    default_search: options.keyword
                })
            }
        });
    },
    // onReady
    onReady: function () {
        const that = this;
        var query = wx.createSelectorQuery();
        query.select(".search-container-top").boundingClientRect(function (rect) {
            that.setData({ search_box_height: rect.height })
        }).exec()
    },
})